import 'dart:convert';

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:industry_net/base/common/keys.dart';
import 'package:industry_net/global/global.dart';
import 'state.dart';
import 'user.dart';

class UserController extends GetxController {
  final state = UserState();
  final GetStorage box = GetStorage();
  @override
  void onInit() {
    super.onInit();
    var _token = GlobalState().token;

    if (_token != null) {
      var _userStr = box.read(key_store_user);
      if (_userStr != null) {
        var _userJson = jsonDecode(_userStr);
        state.user = User.fromJson(_userJson);
      }
    }
  }

  final _isLogin = false.obs;
  set isLogin(bool value) => _isLogin.value = value;
  bool get isLogin => _isLogin.value;

  void save() {
    if (state.user != null) {
      var _json = state.user!.toJson();

      box.write(key_store_user, jsonEncode(_json));
    }
  }
}
